package top.zerozoo.learn.grade.servlet;

import org.apache.commons.beanutils.BeanUtils;
import top.zerozoo.learn.grade.factory.ServiceFactory;
import top.zerozoo.learn.grade.service.MajorService;
import top.zerozoo.learn.grade.service.StudentSimpleInfoService;
import top.zerozoo.learn.grade.util.NumberUtils;
import top.zerozoo.learn.grade.vo.StudentListInfo;
import top.zerozoo.learn.grade.vo.StudentListCondition;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/studentList.do")
public class StudentListServlet extends HttpServlet {
    private final StudentSimpleInfoService studentSimpleInfoService = ServiceFactory.get(StudentSimpleInfoService.class);
    private final MajorService majorService = ServiceFactory.get(MajorService.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int currentPage = NumberUtils.parse(req.getParameter("currentPage"), Integer.class, 1);
        int rows = NumberUtils.parse(req.getParameter("rows"), Integer.class, 20);

        StudentListCondition condition = new StudentListCondition();
        try {
            BeanUtils.populate(condition, req.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }

        StudentListInfo studentListInfo = new StudentListInfo();
        studentListInfo.setPageInfo(studentSimpleInfoService.find(currentPage, rows, condition));
        studentListInfo.setCondition(condition);
        studentListInfo.setMajors(majorService.findAll());

        req.setAttribute("info", studentListInfo);
        req.getRequestDispatcher("/studentList.jsp").forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
